//
//  PKLoginViewController.swift
//  Panku
//
//  Created by mac on 2017/2/7.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import YYKit
import SnapKit

import ReactiveCocoa
import ReactiveSwift
import Result

import SVProgressHUD

class PKLoginViewController: PKBaseViewController {
    
    //MARK: - init
    init(viewModel:PKLoginViewModel){
        super.init(nibName: nil, bundle: nil)
        
        self.viewModel = viewModel
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - properties
    //viewModel
    var viewModel:PKLoginViewModel?
    
    //UI
    lazy var backgroundView = UIImageView()
    lazy var closeButton = PKBaseButton.createButton()
    lazy var forgetPassButton = PKBaseButton.createButton()
    lazy var AvatarView = UIImageView()
    lazy var cellNumberTextField = PKTextField()
    lazy var passwordTextField = PKTextField()
    lazy var loginButton = PKBaseButton.createButton()
    lazy var promptLabel = UILabel()
    
    lazy var wechatButton = PKBaseButton.createButton()
    lazy var qqButton = PKBaseButton.createButton()
    lazy var weiboButton = PKBaseButton.createButton()
    
    lazy var registerButton = PKBaseButton.createButton()
    
    lazy var agreementLabel = UILabel()
    lazy var agreementButton = PKBaseButton.createButton()

    
    //MARK: - life circle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }

    
    //MARK: - UI
    override func setupRootView() {
        view.backgroundColor = UIColor.white
        
        let tapGesture = UITapGestureRecognizer { (_) in
            self.view.endEditing(true)
        }
        
        view.addGestureRecognizer(tapGesture)
    }
    
    override func setupSubViews() {
        view.addSubview(backgroundView)
        view.addSubview(closeButton)
        view.addSubview(AvatarView)
        view.addSubview(cellNumberTextField)
        view.addSubview(passwordTextField)
        view.addSubview(loginButton)
        view.addSubview(promptLabel)
        view.addSubview(wechatButton)
        view.addSubview(qqButton)
        view.addSubview(weiboButton)
        view.addSubview(forgetPassButton)
        view.addSubview(registerButton)
        view.addSubview(agreementLabel)
        view.addSubview(agreementButton)
        
        
        backgroundView.image = R.image.login_background()
        
        closeButton.addBlock(for: .touchUpInside) { (_) in

            self.dismiss(animated: true, completion: { 
                
            })
        }
        
        closeButton.setImage(R.image.login_close(), for: .normal)
        
        AvatarView.image = R.image.login_avatar()
        
        loginButton.layer.cornerRadius = 4
        loginButton.layer.masksToBounds = true
        
        loginButton.titleLabel?.font = UIFont.PKFont(Size: 16)
        loginButton.setTitleColor(UIColor.white, for: .normal)
        loginButton.setTitle("登录", for: .normal)
        loginButton.backgroundColor = UIColor(hexString: "333333")
        loginButton.addBlock(for: .touchUpInside) { (button) in
            let accessId = self.cellNumberTextField.text ?? ""
            let accessType = "FK"
            let passwd = self.passwordTextField.text ?? ""
            
            //hud
            SVProgressHUD.show()
            
            PKLoginServices.login(accessId: accessId, accessType: accessType, passwd: passwd).startWithResult({ (result) in
                
                //dismiss hud
                SVProgressHUD.dismiss()
                
                if result.error != nil{
                    SVProgressHUD.showError(withStatus: result.error?.description)
                }else{
                    //存user_id 存token
                    let dict = result.value as! NSDictionary
                    let ok = dict["ok"] as! Bool
                    
                    if ok == false{
                        SVProgressHUD.showError(withStatus: "登录失败")
                        return
                    }
                    
                    let entity = dict["entity"] as! NSDictionary
                    let id = entity["id"] as! Int
                    let token = entity["token"] as! String
                    
                    PKLoginServices.setUserId(id: id)
                    PKLoginServices.setToken(token: token)
                    
                    SVProgressHUD.showSuccess(withStatus: "登录成功")
                    //dismiss
                    self.dismiss(animated: true, completion: { 
                        
                    })
                }
            })
        }
        
        promptLabel.text = "第三方登录"
        promptLabel.textColor = UIColor(hexString: "4A4A4A")
        promptLabel.font = UIFont.PKFont(Size: 12)
        
        qqButton.setImage(R.image.login_qq(), for: .normal)
        wechatButton.setImage(R.image.login_wechat(), for: .normal)
        weiboButton.setImage(R.image.login_weibo(), for: .normal)
        
        cellNumberTextField.font = UIFont.PKFont(Size: 13)
        cellNumberTextField.textColor = UIColor.black
        cellNumberTextField.dsl_textField_placeholderColor = UIColor(hexString: "B9B9B9")
        cellNumberTextField.placeholder = "请输入您的账号"
        cellNumberTextField.seperationView.backgroundColor = UIColor(hexString: "B9B9B9")
        
        passwordTextField.font = UIFont.PKFont(Size: 13)
        passwordTextField.textColor = UIColor.black
        passwordTextField.dsl_textField_placeholderColor = UIColor(hexString: "B9B9B9")
        passwordTextField.placeholder = "请输入您的密码"
        passwordTextField.seperationView.backgroundColor = UIColor(hexString: "B9B9B9")
        
        registerButton.titleLabel?.font = UIFont.PKFont(Size: 12)
        registerButton.backgroundColor = UIColor.clear
        registerButton.setTitle("注册", for: .normal)
        
        registerButton.setTitleColor(UIColor(hexString: "808080"), for: .normal)
        registerButton.addBlock(for: .touchUpInside) { (_) in
            let registerController = PKRegisterViewController(viewModel: self.viewModel!.viewModelForRegisterViewController())
            self.present(registerController, animated: true, completion: { 
                //finish callback
            })
        }
        
        forgetPassButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        forgetPassButton.setTitleColor(UIColor(hexString: "808080"), for: .normal)
        forgetPassButton.setTitle("忘记密码?", for: .normal)
        forgetPassButton.addBlock(for: .touchUpInside) { (_) in
            let forgetPassController = PLForgetPassViewController()
            self.navigationController?.pushViewController(forgetPassController, animated: true)
        }
        
        agreementLabel.text = "登录即代表你同意放克服务和隐私条款"
        agreementLabel.textColor = UIColor.white
        agreementLabel.font = UIFont.systemFont(ofSize: 10)
    
    }
    
    override func setupSubViewsConstraints() {
        
        backgroundView.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left)
            make.right.equalTo(view.snp.right)
            make.bottom.equalTo(view.snp.bottom)

        }
        
        closeButton.snp.makeConstraints { (make) in
            make.width.equalTo(44)
            make.height.equalTo(44)
            make.top.equalTo(view.snp.top).offset(20)
            make.right.equalTo(view.snp.right)
        }
        
        AvatarView.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.top.equalTo(view.snp.top).offset(91*D_FACTOR_Y)
        }
        
        cellNumberTextField.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.width.equalTo(260*D_FACTOR_X)
            make.top.equalTo(AvatarView.snp.bottom).offset(40*D_FACTOR_Y)
            
        }
        
        passwordTextField.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.width.equalTo(260*D_FACTOR_X)
            make.top.equalTo(cellNumberTextField.snp.bottom).offset(44)
            
        }
        
        loginButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.width.equalTo(260*D_FACTOR_X)
            make.top.equalTo(passwordTextField.snp.bottom).offset(60)
            make.height.equalTo(40)
        }
        
        registerButton.snp.makeConstraints { (make) in
            make.top.equalTo(forgetPassButton.snp.top)
            make.left.equalTo(passwordTextField.snp.left)
        }
        
        promptLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.top.equalTo(registerButton.snp.bottom).offset(70*D_FACTOR_Y)
        }
        
        qqButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.top.equalTo(promptLabel.snp.bottom).offset(17)
        }
        
        wechatButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(qqButton.snp.centerY)
            make.left.equalTo(view.snp.left).offset(60)
        }
        
        weiboButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(qqButton.snp.centerY)
            make.right.equalTo(view.snp.right).offset(-60)
        }
        
        forgetPassButton.snp.makeConstraints { (make) in
            make.top.equalTo(passwordTextField.snp.bottom).offset(10)
            make.right.equalTo(passwordTextField.snp.right)
        }
        
        agreementLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.bottom.equalTo(view.snp.bottom).offset(-20*D_FACTOR_Y)
        }
        
        agreementButton.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left).offset(APP_WIDTH*0.5)
            make.bottom.equalTo(agreementLabel.snp.bottom).offset(7)

        }
        
    }
    
    override func setupNavigationBar() {
        
    }
    
    override func bindViewModel() {

        
//        loginButton.reactive.pressed = CocoaAction(viewModel!.actionForLogin(), { (_) -> (String,String,String) in
//            return (self.cellNumberTextField.text ?? "","PK",self.passwordTextField.text ?? "")
//        })
        
        
        //键盘自动弹出
        self.reactive.trigger(for: #selector(UIViewController.viewDidAppear(_:))).observeValues { (_) in
            self.cellNumberTextField.becomeFirstResponder()
        }
        
        
        
    }


}
